import { ref, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  getUserList, 
  addUser, 
  updateUser, 
  deleteUser 
} from '../apis/user.js';
import { useUserStore } from '../store/modules/user.js';

export default function useEmployeeManagement() {
  // 状态管理
  const loading = ref(false);
  const dialogVisible = ref(false);
  const userFormRef = ref(null);
  const userStore = useUserStore();

  // 搜索表单
  const searchForm = reactive({
    username: '',
    status: ''
  });

  // 分页配置
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  });

  // 员工数据列表
  const employeeDataList = ref([]);

  // 状态选项
  const statusOptions = [
    { label: '禁用', value: 0 },
    { label: '正常', value: 1 }
  ];

  // 员工表单
  const employeeForm = reactive({
    id: '',
    username: '',
    password: '',
    realName: '',
    email: '',
    phone: '',
    userType: 2, // 企业用户
    enterpriseId: null, // 将在初始化时从用户Store获取
    status: '1'
  });

  // 表单验证规则
  const formRules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 50, message: '用户名长度在 3 到 50 个字符', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    realName: [
      { required: true, message: '请输入真实姓名', trigger: 'blur' },
      { max: 50, message: '真实姓名不超过 50 个字符', trigger: 'blur' }
    ],
    email: [
      { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ],
    phone: [
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: ['blur', 'change'] }
    ]
  };

  // 判断是否为编辑模式
  const isEditMode = computed(() => !!employeeForm.id);

  // 对话框标题
  const dialogTitle = computed(() => {
    return isEditMode.value ? '编辑员工' : '新增员工';
  });

  // 初始化企业ID
  const initEnterpriseId = () => {
    const currentUser = userStore.userInfo;
    console.log('currentUser:', currentUser);
    if (currentUser && currentUser.enterpriseId) {
      employeeForm.enterpriseId = currentUser.enterpriseId;
    }
  };

  // 获取员工列表数据（仅获取当前企业的员工）
  const fetchEmployeeData = async () => {
    loading.value = true;
    try {
      // 确保企业ID已设置
      initEnterpriseId();
      
      if (!employeeForm.enterpriseId) {
        ElMessage.error('无法获取企业信息');
        return;
      }
      
      const params = {
        page: pagination.currentPage,
        pageSize: pagination.pageSize,
        // 将空字符串转换为null，避免不必要的参数传递
        username: searchForm.username || undefined,
        userType: 2, // 固定为企业用户
        enterpriseId: employeeForm.enterpriseId, // 仅获取当前企业的员工
        status: searchForm.status !== '' ? Number(searchForm.status) : undefined
      };
      console.log('params:', params);
      
      const response = await getUserList(params);
      
      if (response.code === 200) {
        // 解析后端返回的数据，适配前端需要的格式
        employeeDataList.value = response.data.records || [];
        pagination.total = response.data.total || 0;
      } else {
        ElMessage.error(response.message || '获取员工列表失败');
      }
    } catch (error) {
      console.error('获取员工列表失败:', error);
      ElMessage.error('获取员工列表失败');
    } finally {
      loading.value = false;
    }
  };

  // 重置表单
  const resetForm = () => {
    if (userFormRef.value) {
      userFormRef.value.resetFields();
    }
    // 重置时保持企业ID
    const currentEnterpriseId = employeeForm.enterpriseId;
    Object.assign(employeeForm, {
      id: '',
      username: '',
      password: '',
      realName: '',
      email: '',
      phone: '',
      userType: 2,
      enterpriseId: currentEnterpriseId,
      status: '1'
    });
  };

  // 打开新增员工对话框
  const handleAddEmployee = () => {
    initEnterpriseId();
    resetForm();
    dialogVisible.value = true;
  };

  // 打开编辑员工对话框
  const handleEditEmployee = (employee) => {
    resetForm();
    Object.assign(employeeForm, {
      ...employee,
      status: String(employee.status) // 转换为字符串以便switch组件使用
    });
    dialogVisible.value = true;
  };

  // 提交表单
  const handleFormSubmit = async () => {
    if (!userFormRef.value) return;
    
    try {
      await userFormRef.value.validate();
      
      loading.value = true;
      
      // 准备提交数据
      const submitData = { ...employeeForm };
      
      // 处理状态字段转换
      submitData.status = Number(submitData.status);
      
      // 如果密码为空且是编辑模式，则删除密码字段
      if (isEditMode.value && !submitData.password) {
        delete submitData.password;
      }
      
      if (isEditMode.value) {
        // 编辑员工
        const response = await updateUser(employeeForm.id, submitData);
        if (response.code === 200) {
          ElMessage.success('编辑员工成功');
          dialogVisible.value = false;
          fetchEmployeeData(); // 重新获取数据
        } else {
          ElMessage.error(response.message || '编辑员工失败');
        }
      } else {
        // 新增员工
        const response = await addUser(submitData);
        if (response.code === 200) {
          ElMessage.success('新增员工成功');
          dialogVisible.value = false;
          fetchEmployeeData(); // 重新获取数据
        } else {
          ElMessage.error(response.message || '新增员工失败');
        }
      }
    } catch (error) {
      console.error('提交表单失败:', error);
      if (error === false) {
        // 验证失败，不显示错误信息
      } else {
        ElMessage.error('操作失败');
      }
    } finally {
      loading.value = false;
    }
  };

  // 删除员工
  const handleDeleteEmployee = (employee) => {
    ElMessageBox.confirm(
      `确定要删除员工「${employee.username}」吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
      .then(async () => {
        loading.value = true;
        try {
          const response = await deleteUser(employee.id);
          if (response.code === 200) {
            ElMessage.success('删除员工成功');
            fetchEmployeeData(); // 重新获取数据
          } else {
            ElMessage.error(response.message || '删除员工失败');
          }
        } catch (error) {
          console.error('删除员工失败:', error);
          ElMessage.error('删除员工失败');
        } finally {
          loading.value = false;
        }
      })
      .catch(() => {
        // 用户取消删除
      });
  };

  // 关闭对话框
  const handleDialogClose = () => {
    if (userFormRef.value) {
      userFormRef.value.resetFields();
    }
  };

  // 搜索
  const handleSearch = () => {
    pagination.currentPage = 1;
    fetchEmployeeData();
  };

  // 重置搜索
  const resetSearch = () => {
    Object.assign(searchForm, {
      username: '',
      status: ''
    });
    pagination.currentPage = 1;
    fetchEmployeeData();
  };

  // 分页大小变化
  const handleSizeChange = (size) => {
    pagination.pageSize = size;
    fetchEmployeeData();
  };

  // 当前页码变化
  const handleCurrentChange = (current) => {
    pagination.currentPage = current;
    fetchEmployeeData();
  };

  // 获取员工状态标签类型
  const getEmployeeStatusTagType = (status) => {
    return status === 1 ? 'success' : 'danger';
  };

  // 获取员工状态标签
  const getEmployeeStatusLabel = (status) => {
    return status === 1 ? '正常' : '禁用';
  };

  return {
    // 状态
    loading,
    dialogVisible,
    userFormRef,
    // 数据
    searchForm,
    pagination,
    employeeDataList,
    statusOptions,
    employeeForm,
    formRules,
    // 计算属性
    isEditMode,
    dialogTitle,
    // 方法
    fetchEmployeeData,
    resetForm,
    handleAddEmployee,
    handleEditEmployee,
    handleFormSubmit,
    handleDeleteEmployee,
    handleDialogClose,
    handleSearch,
    resetSearch,
    handleSizeChange,
    handleCurrentChange,
    getEmployeeStatusTagType,
    getEmployeeStatusLabel,
    initEnterpriseId
  };
}